using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace SolarWinds.Widgets
{
    public class FPSDisplay : Window
    {
        private float mCurrentFPS;
        private float mBestFPS = float.MinValue;
        private float mWorstFPS = float.MaxValue;
        private float mAverageFPS;

        private float mDeltaFPSTime;
        private const float ResetFPSTime = 1.0f;

        public FPSDisplay(Game game)
            : base(game)
        {
            Resizeable = false;

            BoundingRect = new Rectangle(10, 10, 200, 105);
            Caption = "Framerates";
        }

        protected internal override void PaintEvent()
        {
            base.PaintEvent();

            float height = Font.MeasureString(Caption).Y;

            var col1 = new Vector2(ScreenPosition.X + 20, ScreenPosition.Y + 15);
            var col2 = new Vector2(ScreenPosition.X + 140, ScreenPosition.Y + 15);

            SpriteBatch.DrawString(Font, "Current FPS: ", col1, Color.White);
            SpriteBatch.DrawString(Font, mCurrentFPS.ToString("N2"), col2, Color.White);
            col1.Y += height; col2.Y += height;

            SpriteBatch.DrawString(Font, "Best FPS: ", col1, Color.White);
            SpriteBatch.DrawString(Font, mBestFPS.ToString("N2"), col2, Color.White);
            col1.Y += height; col2.Y += height;

            SpriteBatch.DrawString(Font, "Worst FPS: ", col1, Color.White);
            SpriteBatch.DrawString(Font, mWorstFPS.ToString("N2"), col2, Color.White);
            col1.Y += height; col2.Y += height;

            SpriteBatch.DrawString(Font, "Average FPS: ", col1, Color.White);
            SpriteBatch.DrawString(Font, mAverageFPS.ToString("N2"), col2, Color.White);
        }

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            // calculate fps
            var elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

            float currentFPS = 1 / elapsed;
            mDeltaFPSTime += elapsed;

            if (mDeltaFPSTime > ResetFPSTime)
            {
                mAverageFPS = (mAverageFPS + currentFPS) / 2;

                if (currentFPS > mBestFPS)
                {
                    mBestFPS = currentFPS;
                }
                if (currentFPS < mWorstFPS)
                {
                    mWorstFPS = currentFPS;
                }

                mCurrentFPS = currentFPS;

                mDeltaFPSTime -= ResetFPSTime;
            }

            base.Update(gameTime);
        }
    }
}